<template>
    <el-form ref="formRef" :model="computedFormData" label-width="120px" :rules="props.rules" :label-position="props.labelPosition">
        <el-form-item v-for="formItem in computedFormList" :key="formItem.key" :label="formItem.label" :prop="formItem.key">
            <el-input v-if="formItem.type === 'input'" :placeholder="formItem.placeholder || `请输入${formItem.label}`"
                v-model="computedFormData[formItem.key]" :type="formItem.input_type" :show-password="formItem.input_type === 'password'" />
            <el-select v-if="formItem.type === 'select'" v-model="computedFormData[formItem.key]"
                :placeholder="formItem.placeholder || `请选择${formItem.label}`">
                <el-option v-for="selectItem in formItem.selectOptions" :key="selectItem.value" :label="selectItem.label"
                    :value="selectItem.value" />
            </el-select>
            <el-date-picker v-if="formItem.type === 'date-picker'" v-model="computedFormData[formItem.key]" type="date"
                :placeholder="formItem.placeholder || `请选择${formItem.label}`" />
            <el-radio-group v-if="formItem.type === 'radio-group'" v-model="computedFormData[formItem.key]">
                <el-radio v-for="radioItem in formItem.radioOptions" :label="radioItem.value">{{ radioItem.label
                }}</el-radio>
            </el-radio-group>
        </el-form-item>
    </el-form>
</template>
<script>
export default defineComponent({
    name: 'Form',
});
</script>
<script setup>

const props = defineProps({
    formList: {
        type: Array,
        default: [],
    },
    formData: {
        type: Object,
        default: {},
    },
    rules: {
        type: Object,
        default: {},
    },
    labelPosition: {
        type: String,
        default: "left"
    }
})
const emits = defineEmits(['update:formData'])

const formRef = ref();

// 表单渲染列表
const computedFormList = computed(() => {
    return props.formList
})
// 表单数据
const computedFormData = computed({
    get() {
        return props.formData || {};
    },
    set(v) {
        emit("update:formData", v);
    },
});

// 校验表单
const checkForm = () => {
    return new Promise(async (resolve, reject) => {
        const value = await formRef.value.validate()
        if (value) {
            resolve(true);
        } else {
            reject(false);
        }
    })
}
// 重置表单
const resetForm = () => {
    formRef.value.resetField()
}
// 移除表单校验结果
const clearValidate = () => {
    formRef.value.clearValidate()
}

defineExpose({ checkForm, resetForm, clearValidate })
</script>
<style lang='less' scoped>
</style>
